# !/usr/bin/python
# -*- coding: UTF-8 -*-

import os
import sys
from pylab import *
import numpy as np
import matplotlib
import matplotlib.colors as colors
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

def mkmkdowntable(filepath,filepath2):
    
    str1 = filepath.split('/')[-1].split('.')[0].split('_')[-1]
    str2 = filepath2.split('/')[-1].split('.')[0].split('_')[-1]
    
    #print str1,str2
    
    fs = open(filepath,'rb')
    lines = fs.readlines()
    fs.close()
    fs2 = open(filepath2,'rb')
    lines2 = fs2.readlines()
    fs2.close()
    if os.path.split(sys.argv[2])[0] == '':
        fo = open('BluetoothTestReport'+'_'+str1+'.md','wb')
    else:
        fo = open(os.path.split(sys.argv[2])[0] + '/' + 'BluetoothTestReport'+'_'+str1+'.md','wb')
    
    fo.write("## Bluetooth Test Report\r\n")
    fo.write("物理地址 | 发射功率(dB) | 测试距离(m) | 遮挡状况 | 平均信号强度 | 应收包数 | 实收包数 | 丢包率(%) " + str1 + " | 对比丢包率(%) " + str2 + "\r\n")
    fo.write("-------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- \r\n")
    pplk1 = 0
    pplk2 = 0
    count = 0
    aaaaa = {'mac':[],'plk1':[],'plk2':[]}
    for i in range(0,len(lines)):
        if lines[i][0] == '$':
            for j in range(0,len(lines2)):
                if lines[i].split()[lines[i].split().index('mac') + 1].lower() == lines2[j].split()[lines2[j].split().index('mac') + 1].lower():
                    fo.write("%s | %s | %s | %s | %s | %s | %s | %s | %s\r\n" % 
                            (lines[i].split()[lines[i].split().index('mac') + 1],
                             lines[i].split()[lines[i].split().index('power') + 1],
                             lines[i].split()[lines[i].split().index('dist') + 1],
                             lines[i].split()[lines[i].split().index('occl') + 1],
                             lines[i].split()[lines[i].split().index('rssi') + 1],
                             lines[i].split()[lines[i].split().index('nor') + 1],
                             lines[i].split()[lines[i].split().index('apc') + 1],
                             lines[i].split()[lines[i].split().index('plk') + 1],
                             lines2[j].split()[lines2[j].split().index('plk') + 1]) )
                    pplk1 += float(lines[i].split()[lines[i].split().index('plk') + 1])
                    pplk2 += float(lines2[j].split()[lines2[j].split().index('plk') + 1])
                    count += 1
                    aaaaa['mac'].append(lines[i].split()[lines[i].split().index('mac') + 1])
                    aaaaa['plk1'].append(lines[i].split()[lines[i].split().index('plk') + 1])
                    aaaaa['plk2'].append(lines2[j].split()[lines2[j].split().index('plk') + 1])
            #print "-w",lines[i].split()[lines[i].split().index('mac') + 1],"-s","10_00_no"        

    fo.write("%s |   |   |   |   |   |   | %s | %s\r\n" %('平均数',pplk1/count,pplk2/count))
    fo.write("### %s 与 %s 每个设备丢包率的对比如下：\r\n" % (str1,str2))
    fo.write("------\r\n ![](image/data/%s)\r\n" % ('Contrast_' + str1 + '_' + str2 + '.jpg'))
    fo.write("### %s 接收到的所有设备接收数据状况如下\r\n" % (str1))
    for i in range(0,len(lines)):
        if lines[i][0] == '$':
            fo.write("##### %s 接收数据状况如下\r\n" % (lines[i].split()[lines[i].split().index('mac') + 1]))
            fo.write(" ![](image/data/%s_10_00_no.jpg)\r\n" % ('_'.join(lines[i].split()[lines[i].split().index('mac') + 1].split(':'))))
        

    fo.close()
    
    ax = plt.figure(num=1, figsize=(24, 12)).add_subplot(111)
    ax.set_title(str1 + '-' + str2 + ' device packet loss')
    # 设置y轴范围
    ylim(0,100)
    plt.xlabel('Device MAC')
    plt.ylabel('Packet Loss (%)')
    x = range(len(aaaaa['mac']))
    plt.grid(True)
    plt.plot(x, aaaaa['plk1'], 'bo-',label = str1)
    plt.plot(x, aaaaa['plk2'], 'ro-',label = str2)
    plt.xticks(x, aaaaa['mac'], rotation=45)
    plt.margins(0.08)
    plt.subplots_adjust(bottom=0.15)
    ax.legend(loc='upper right') 
    if os.path.split(sys.argv[2])[0] == '':
        plt.savefig('Contrast_' + str1 + '_' + str2 + '.jpg')
    else:
        plt.savefig(os.path.split(sys.argv[2])[0] + '/' + 'Contrast_' + str1 + '_' + str2 + '.jpg')
    plt.show()
    #print aaaaa
    return

if __name__ == '__main__':
           
    mkmkdowntable(sys.argv[1],sys.argv[2])

    print 'over'


